import json
from dtcloud.fields import Field
from dtcloud.models import Model
from .BaseConvert import Convert


class SerializedConvert(Convert):
    field_type = 'serialized'

    _default_json_mapping = {
        dict: {},
        list: [],
        tuple: []
    }

    @classmethod
    def to_read(cls, rec: Model, field: Field, **kwargs):
        return rec[field.name] or cls._default_json_mapping.get(field.base_type, {})

    @classmethod
    def to_field(cls, value, metadata=None, update=False):
        if isinstance(value, (dict, list, tuple)):
            return json.dumps(value)
        else:
            return value or None
